{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Token_Classification_Named_Entity_Recognition.ipynb",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU",
    "pycharm": {
      "stem_cell": {
        "cell_type": "raw",
        "source": [],
        "metadata": {
          "collapsed": false
        }
      }
    }
  },
  "cells": [
    {
     "cell_type": "code",
     "execution_count": null,
     "metadata": {},
     "outputs": [],
     "source": [
     "BRANCH = 'v1.0.0'"
     ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "o_0K1lsW1dj9",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "\"\"\"\n",
        "# If you're using Google Colab and not running locally, run this cell\n",
        "\n",
        "# install NeMo\n",
        "BRANCH = 'v1.0.0'\n!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "pycharm": {
          "name": "#%%\n"
        },
        "id": "pC0slAc0h9zN",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
        "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
        "\n",
        "! pip install ipywidgets\n",
        "! jupyter nbextension enable --py widgetsnbextension\n",
        "\n",
        "# Please restart the kernel after running this cell"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "dzqD2WDFOIN-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "from nemo.collections import nlp as nemo_nlp\n",
        "from nemo.utils.exp_manager import exp_manager\n",
        "\n",
        "import os\n",
        "import wget \n",
        "import torch\n",
        "import pytorch_lightning as pl\n",
        "from omegaconf import OmegaConf"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "daYw_Xll2ZR9",
        "colab_type": "text"
      },
      "source": [
        "# Task Description\n",
        "**Named entity recognition (NER)**, also referred to as entity chunking, identification or extraction, is the task of detecting and classifying key information (entities) in text.\n",
        "For example, in a sentence:  `Mary lives in Santa Clara and works at NVIDIA`, we should detect that `Mary` is a person, `Santa Clara` is a location and `NVIDIA` is a company."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZnuziSwJ1yEB",
        "colab_type": "text"
      },
      "source": [
        "# Dataset\n",
        "\n",
        "In this tutorial we going to use [GMB(Groningen Meaning Bank)](http://www.let.rug.nl/bjerva/gmb/about.php) corpus for entity recognition. \n",
        "\n",
        "GMB is a fairly large corpus with a lot of annotations. Note, that GMB is not completely human annotated and it’s not considered 100% correct. \n",
        "The data is labeled using the [IOB format](https://en.wikipedia.org/wiki/Inside%E2%80%93outside%E2%80%93beginning_(tagging)) (short for inside, outside, beginning). \n",
        "\n",
        "The following classes appear in the dataset:\n",
        "* LOC = Geographical Entity\n",
        "* ORG = Organization\n",
        "* PER = Person\n",
        "* GPE = Geopolitical Entity\n",
        "* TIME = Time indicator\n",
        "* ART = Artifact\n",
        "* EVE = Event\n",
        "* NAT = Natural Phenomenon\n",
        "\n",
        "For this tutorial, classes ART, EVE, and NAT were combined into a MISC class due to small number of examples for these classes.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qzcZ3nb_-SVT",
        "colab_type": "text"
      },
      "source": [
        "# NeMo Token Classification Data Format\n",
        "\n",
        "[TokenClassification Model](https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/nlp/models/token_classification/token_classification_model.py) in NeMo supports NER and other token level classification tasks, as long as the data follows the format specified below. \n",
        "\n",
        "Token Classification Model requires the data to be split into 2 files: \n",
        "* text.txt and \n",
        "* labels.txt. \n",
        "\n",
        "Each line of the **text.txt** file contains text sequences, where words are separated with spaces, i.e.: \n",
        "[WORD] [SPACE] [WORD] [SPACE] [WORD].\n",
        "\n",
        "The **labels.txt** file contains corresponding labels for each word in text.txt, the labels are separated with spaces, i.e.:\n",
        "[LABEL] [SPACE] [LABEL] [SPACE] [LABEL].\n",
        "\n",
        "Example of a text.txt file:\n",
        "```\n",
        "Jennifer is from New York City .\n",
        "She likes ...\n",
        "...\n",
        "```\n",
        "Corresponding labels.txt file:\n",
        "```\n",
        "B-PER O O B-LOC I-LOC I-LOC O\n",
        "O O ...\n",
        "...\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VsEmwIPO4L4V",
        "colab_type": "text"
      },
      "source": [
        "To convert an IOB format data to the format required for training, run [examples/nlp/token_classification/data/import_from_iob_format.py](https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/data/import_from_iob_format.py) on your train and dev files, as follows:\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "```\n",
        "python examples/nlp/token_classification/data/import_from_iob_format.py --data_file PATH_TO_IOB_FORMAT_DATAFILE\n",
        "```\n",
        "\n",
        "For this tutorial, we are going to use the preprocessed GMB dataset.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SL58EWkd2ZVb",
        "colab_type": "text"
      },
      "source": [
        "## Download and preprocess the data¶"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "n8HZrDmr12_-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "DATA_DIR = \"DATA_DIR\"\n",
        "WORK_DIR = \"WORK_DIR\"\n",
        "MODEL_CONFIG = \"token_classification_config.yaml\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jrx2ZXHrCHb_",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# download preprocessed data\n",
        "os.makedirs(WORK_DIR, exist_ok=True)\n",
        "os.makedirs(DATA_DIR, exist_ok=True)\n",
        "print('Downloading GMB data...')\n",
        "wget.download('https://dldata-public.s3.us-east-2.amazonaws.com/gmb_v_2.2.0_clean.zip', DATA_DIR)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NhUzIeF0Yg0l",
        "colab_type": "text"
      },
      "source": [
        "Let's extract files from the .zip file:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y01BdjPRW-7B",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "! unzip {DATA_DIR}/gmb_v_2.2.0_clean.zip -d {DATA_DIR}\n",
        "DATA_DIR = os.path.join(DATA_DIR, 'gmb_v_2.2.0_clean')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "U8Ty5_S7Ye8h",
        "colab_type": "text"
      },
      "source": [
        "Now, the data folder should contain 4 files:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L8vsyh3JZH26",
        "colab_type": "text"
      },
      "source": [
        "\n",
        "\n",
        "* labels_dev.txt\n",
        "* labels_train.txt\n",
        "* text_dev.txt\n",
        "* text_train.txt\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qB0oLE4R9EhJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "! ls -l {DATA_DIR}"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6UDPgadLN6SG",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's take a look at the data \n",
        "print('Text:')\n",
        "! head -n 5 {DATA_DIR}/text_train.txt\n",
        "\n",
        "print('\\nLabels:')\n",
        "! head -n 5 {DATA_DIR}/labels_train.txt"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "daludzzL2Jba",
        "colab_type": "text"
      },
      "source": [
        "# Model Configuration"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tit5kG4Z5SXu",
        "colab_type": "text"
      },
      "source": [
        "# Using an Out-of-the-Box Model\n",
        "\n",
        "To use a pretrained NER model, run:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BKe5Jn4u9xng",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# this line will download pre-trained NER model from NVIDIA's NGC cloud and instantiate it for you\n",
        "pretrained_ner_model = nemo_nlp.models.TokenClassificationModel.from_pretrained(model_name=\"ner_en_bert\") "
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "y8SFxPJd-hkH"
      },
      "source": [
        "To see how the model performs, let’s get model's predictions for a few examples:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DQhsamclRtxJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# define the list of queries for inference\n",
        "queries = [\n",
        "    'we bought four shirts from the nvidia gear store in santa clara.',\n",
        "    'Nvidia is a company.',\n",
        "    'The Adventures of Tom Sawyer by Mark Twain is an 1876 novel about a young boy growing '\n",
        "    + 'up along the Mississippi River.',\n",
        "]\n",
        "results = pretrained_ner_model.add_predictions(queries)\n",
        "\n",
        "for query, result in zip(queries, results):\n",
        "    print()\n",
        "    print(f'Query : {query}')\n",
        "    print(f'Result: {result.strip()}\\n')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_whKCxfTMo6Y",
        "colab_type": "text"
      },
      "source": [
        "Now, let's take a closer look at the model's configuration and learn to train the model from scratch and finetune the pretrained model.\n",
        "\n",
        "# Model configuration\n",
        "\n",
        "Our Named Entity Recognition model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Token Classification layer.\n",
        "\n",
        "The model is defined in a config file which declares multiple important sections. They are:\n",
        "- **model**: All arguments that are related to the Model - language model, token classifier, optimizer and schedulers, datasets and any other related information\n",
        "\n",
        "- **trainer**: Any argument to be passed to PyTorch Lightning"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "T1gA8PsJ13MJ",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# download the model's configuration file \n",
        "config_dir = WORK_DIR + '/configs/'\n",
        "os.makedirs(config_dir, exist_ok=True)\n",
        "if not os.path.exists(config_dir + MODEL_CONFIG):\n",
        "    print('Downloading config file...')\n",
        "    wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/token_classification/conf/' + MODEL_CONFIG, config_dir)\n",
        "else:\n",
        "    print ('config file is already exists')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mX3KmWMvSUQw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# this line will print the entire config of the model\n",
        "config_path = f'{WORK_DIR}/configs/{MODEL_CONFIG}'\n",
        "print(config_path)\n",
        "config = OmegaConf.load(config_path)\n",
        "print(OmegaConf.to_yaml(config))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZCgWzNBkaQLZ",
        "colab_type": "text"
      },
      "source": [
        "# Model Training From Scratch\n",
        "## Setting up Data within the config\n",
        "\n",
        "Among other things, the config file contains dictionaries called dataset, train_ds and validation_ds. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
        "\n",
        "We assume that both training and evaluation files are located in the same directory, and use the default names mentioned during the data download step. \n",
        "So, to start model training, we simply need to specify `model.dataset.data_dir`, like we are going to do below.\n",
        "\n",
        "Also notice that some config lines, including `model.dataset.data_dir`, have `???` in place of paths, this means that values for these fields are required to be specified by the user.\n",
        "\n",
        "Let's now add the data directory path to the config."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LQHCJN-ZaoLp",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# in this tutorial train and dev datasets are located in the same folder, so it is enought to add the path of the data directory to the config\n",
        "config.model.dataset.data_dir = DATA_DIR\n",
        "\n",
        "# if you want to use the full dataset, set NUM_SAMPLES to -1\n",
        "NUM_SAMPLES = 1000\n",
        "config.model.train_ds.num_samples = NUM_SAMPLES\n",
        "config.model.validation_ds.num_samples = NUM_SAMPLES"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nB96-3sTc3yk",
        "colab_type": "text"
      },
      "source": [
        "## Building the PyTorch Lightning Trainer\n",
        "\n",
        "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.\n",
        "\n",
        "Let's first instantiate a Trainer object"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1tG4FzZ4Ui60",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "print(\"Trainer config - \\n\")\n",
        "print(OmegaConf.to_yaml(config.trainer))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "knF6QeQQdMrH",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# lets modify some trainer configs\n",
        "# checks if we have GPU available and uses it\n",
        "cuda = 1 if torch.cuda.is_available() else 0\n",
        "config.trainer.gpus = cuda\n",
        "\n",
        "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
        "\n",
        "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
        "# config.trainer.amp_level = O1\n",
        "\n",
        "# remove distributed training flags\n",
        "config.trainer.accelerator = None\n",
        "\n",
        "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
        "config.trainer.max_steps = 32\n",
        "\n",
        "trainer = pl.Trainer(**config.trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8IlEMdVxdr6p",
        "colab_type": "text"
      },
      "source": [
        "## Setting up a NeMo Experiment¶\n",
        "\n",
        "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8uztqGAmdrYt",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
        "\n",
        "# the exp_dir provides a path to the current experiment for easy access\n",
        "exp_dir = str(exp_dir)\n",
        "exp_dir"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8tjLhUvL_o7_",
        "colab_type": "text"
      },
      "source": [
        "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Xeuc2i7Y_nP5",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# get the list of supported BERT-like models, for the complete list of HugginFace models, see https://huggingface.co/models\n",
        "print(nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True))\n",
        "\n",
        "# specify BERT-like model, you want to use\n",
        "PRETRAINED_BERT_MODEL = \"bert-base-uncased\""
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RK2xglXyAUOO",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# add the specified above model parameters to the config\n",
        "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fzNZNAVRjDD-",
        "colab_type": "text"
      },
      "source": [
        "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
        "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NgsGLydWo-6-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "model_from_scratch = nemo_nlp.models.TokenClassificationModel(cfg=config.model, trainer=trainer)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kQ592Tx4pzyB",
        "colab_type": "text"
      },
      "source": [
        "## Monitoring training progress\n",
        "Optionally, you can create a Tensorboard visualization to monitor training progress."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mTJr16_pp0aS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  from google import colab\n",
        "  COLAB_ENV = True\n",
        "except (ImportError, ModuleNotFoundError):\n",
        "  COLAB_ENV = False\n",
        "\n",
        "# Load the TensorBoard notebook extension\n",
        "if COLAB_ENV:\n",
        "  %load_ext tensorboard\n",
        "  %tensorboard --logdir {exp_dir}\n",
        "else:\n",
        "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "hUvnSpyjp0Dh",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# start model training\n",
        "trainer.fit(model_from_scratch)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JxBiIKMlH8yv",
        "colab_type": "text"
      },
      "source": [
        "After training for 5 epochs, with the default config and NUM_SAMPLES = -1 (i.e.all data is used), your model performance should look similar to this: \n",
        "```\n",
        "    label                                                precision    recall       f1           support   \n",
        "    O (label_id: 0)                                         99.14      99.19      99.17     131141\n",
        "    B-GPE (label_id: 1)                                     95.86      94.03      94.93       2362\n",
        "    B-LOC (label_id: 2)                                     83.99      90.31      87.04       5346\n",
        "    B-MISC (label_id: 3)                                    39.82      34.62      37.04        130\n",
        "    B-ORG (label_id: 4)                                     78.33      67.82      72.70       2980\n",
        "    B-PER (label_id: 5)                                     84.36      84.32      84.34       2577\n",
        "    B-TIME (label_id: 6)                                    91.94      91.23      91.58       2975\n",
        "    I-GPE (label_id: 7)                                     88.89      34.78      50.00         23\n",
        "    I-LOC (label_id: 8)                                     77.18      79.13      78.14       1030\n",
        "    I-MISC (label_id: 9)                                    28.57      24.00      26.09         75\n",
        "    I-ORG (label_id: 10)                                    78.67      75.67      77.14       2384\n",
        "    I-PER (label_id: 11)                                    86.69      90.17      88.40       2687\n",
        "    I-TIME (label_id: 12)                                   83.21      83.48      83.34        938\n",
        "    -------------------\n",
        "    micro avg                                               96.95      96.95      96.95     154648\n",
        "    macro avg                                               78.20      72.98      74.61     154648\n",
        "    weighted avg                                            96.92      96.95      96.92     154648\n",
        "```\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VPdzJVAgSFaJ",
        "colab_type": "text"
      },
      "source": [
        "# Inference\n",
        "\n",
        "To see how the model performs, we can run generate prediction similar to the way we did it earlier"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QaW0A1OOwefR",
        "colab_type": "text"
      },
      "source": [
        "## Generate Predictions\n",
        "\n",
        "To see how the model performs, we can generate prediction the same way we did it earlier or we can use our model to generate predictions for a dataset from a file, for example, to perform final evaluation or to do error analysis.\n",
        "Below, we are using a subset of dev set, but it could be any text file as long as it follows the data format described above.\n",
        "Labels_file is optional here, and if provided will be used to get metrics."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "92PB0iTqNnW-",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's first create a subset of our dev data\n",
        "! head -n 100 {DATA_DIR}/text_dev.txt > {DATA_DIR}/sample_text_dev.txt\n",
        "! head -n 100 {DATA_DIR}/labels_dev.txt > {DATA_DIR}/sample_labels_dev.txt"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vXnx2tKoOohy",
        "colab_type": "text"
      },
      "source": [
        "Now, let's generate predictions for the provided text file.\n",
        "If labels file is also specified, the model will evaluate the predictions and plot confusion matrix. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sglcZV1bwsv0",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "model_from_scratch.evaluate_from_file(\n",
        "    text_file=os.path.join(DATA_DIR, 'sample_text_dev.txt'),\n",
        "    labels_file=os.path.join(DATA_DIR, 'sample_labels_dev.txt'),\n",
        "    output_dir=exp_dir,\n",
        ")"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ref1qSonGNhP",
        "colab_type": "text"
      },
      "source": [
        "## Training Script\n",
        "\n",
        "If you have NeMo installed locally, you can also train the model with [nlp/token_classification/token_classification_train.py](https://github.com/NVIDIA/NeMo/blob/main/examples/nlp/token_classification/token_classification_train.py).\n",
        "\n",
        "To run training script, use:\n",
        "\n",
        "`python token_classification_train.py model.dataset.data_dir=PATH_TO_DATA_DIR`\n",
        "\n",
        "# Finetuning model with your data\n",
        "\n",
        "When we were training from scratch, the datasets were prepared for training during the model initialization. When we are using a pretrained NER model, before training, we need to setup training and evaluation data.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yu9fZc2vPQfw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# let's reload our pretrained NER model\n",
        "pretrained_ner_model = nemo_nlp.models.TokenClassificationModel.from_pretrained('ner_en_bert')\n",
        "\n",
        "# then we need to setup the data dir to get class weights statistics\n",
        "pretrained_ner_model.update_data_dir(DATA_DIR)\n",
        "\n",
        "# setup train and validation Pytorch DataLoaders\n",
        "pretrained_ner_model.setup_training_data()\n",
        "pretrained_ner_model.setup_validation_data()\n",
        "\n",
        "# then we're setting up loss, use class_balancing='weighted_loss' if you want to add class weights to the CrossEntropyLoss\n",
        "pretrained_ner_model.setup_loss()\n",
        "\n",
        "# and now we can create a PyTorch Lightning trainer and call `fit` again\n",
        "# for this tutorial we are setting fast_dev_run to True, and the trainer will run 1 training batch and 1 validation batch\n",
        "# for actual model training, disable the flag\n",
        "fast_dev_run = True\n",
        "trainer = pl.Trainer(gpus=1, fast_dev_run=fast_dev_run)\n",
        "trainer.fit(pretrained_ner_model)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "source": [
        "# Labeling your own data\n",
        "\n",
        "If you have raw data, NeMo recommends using the Datasaur labeling platform to apply labels to data. Datasaur was designed specifically for labeling text data and supports basic NLP labeling tasks such as Named Entity Recognition and text classification through advanced NLP tasks such as dependency parsing and coreference resolution. You can sign up for Datasaur for free at https://datasaur.ai/sign-up/. Once you upload a file, you can choose from multiple NLP project types and use the Datasaur interface to label the data. After labeling, you can export the labeled data using the conll_2003 format, which integrates directly with NeMo. A video walkthrough can be found here: https://www.youtube.com/watch?v=I9WVmnnSciE.\n"
      ],
      "cell_type": "markdown",
      "metadata": {}
    }
  ]
}
